import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/home/HomeViewModel.dart';
import 'package:flutter_ahj_app/app/my/Beans/CheckDataVersionData.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/utils/ApkUpdataUtils.dart';
import 'package:flutter_ahj_app/base/utils/HttpUtils.dart';
import 'package:flutter_ahj_app/app/HttpRequest.dart';

import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/zjTopBar.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';


class HomeView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return HomeViewState();
  }
}

class HomeViewState extends BaseState<HomeViewModel, HomeView> {
  List _gztData = ['创建任务', '隐患登记', '排查任务', '隐患治理'];
  CheckDataVersionData version;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getStatus();
    Future.delayed(Duration.zero, () {
      _checkVersion();
      _caidan();
    });
  }

  _caidan() {
    viewModel.getHomeMoudle();
    viewModel.getHomeMoudleStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          _gztData.clear();
          for (var i = 0; i < event['data'].length; i++) {
            _gztData.add(event['data'][i]['name']);
          }
        });
      }
    }, onError: (e) {
      print(e);
    });
  }

  _getStatus() async {
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      return ToastUtils.showToast("请检查手机网络设置");
    }
  }

  _checkVersion() async{
    if (HttpBaseConst.serverUrl.contains("api.platform.anhuanjia.com")) {
      String result =
          await PerUtils.checkPermission(context, [Permission.storage]);
      if (result == "1" && Platform.isAndroid) {
        _checkVersionData();
      }
    }
    // else {
    //   _checkVersionData();//测试环境
    // }
  }

  Future _checkVersionData() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    var _DATA = {
      'version': packageInfo.version,
    };
    HttpRequest.checkVersion(_DATA).listen((request) {
      version = CheckDataVersionData.fromJson(request);
      if(version.code == "0") {
        if (version.data.updateState) {
          // 不是最新版本
          _askedToLead(context, version.data);
        } else {
          // ToastUtils.showToast("已是最新版本");
        }
      }else {
        ToastUtils.showToast(version.msg);
      }
    }, onError: (e) {
      //请求异常等
      print(e);
    });
  }

  @override
  Widget initWidget() {
    return Container(
      decoration: BoxDecoration(
          color: Color(0x00f6f7f8),
          boxShadow: [
            BoxShadow(
              blurRadius: 15, //阴影范围
              spreadRadius: 3, //阴影浓度
              color: Colors.black12, //阴影颜色
            ),
          ],
          image: DecorationImage(
              fit: BoxFit.fitWidth,
              image: AssetImage(
                "img/home_back.png",
              ))),
      child: Scaffold(
        backgroundColor: Color(0x00f6f7f8),
        appBar: ZJTopBar(
          backgroundColor: Color(0x00f6f7f8),
          elevation: 0,
          title: '鑫安云',
        ).create(),
        body: _bodyView(),
      ),
    );
  }

  _bodyView() {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(top: 25),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  children: [
                    InkWell(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Color(0x00f6f7f8),
                            boxShadow: [
                              BoxShadow(
                                blurRadius: 16, //阴影范围
                                spreadRadius: 1, //阴影浓度
                                color: Color(0x16479DE4), //阴影颜色
                              )
                            ]),child: Image.asset("img/home_db.png",
                        width: Dimens.dimens50,
                        height: Dimens.dimens50,
                      ),),
                      onTap: () {
                        bool _isLogin = isEmpty(UserInfoUtils.getUserToken());
                        if (_isLogin) {
                          Navigator.pushNamed(context, "/LoginPageView");
                          return;
                        }
                        Navigator.pushNamed(context, "/DbPageView");
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5),
                      child: JText(
                        '待办',
                        color: Color(0xff3A4A61),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Column(
                  children: [
                    InkWell(
                      child: Container(child: Image.asset(
                        "img/home_fq.png",
                        width: Dimens.dimens50,
                        height: Dimens.dimens50,
                      ), decoration: BoxDecoration(
                          color: Color(0x00f6f7f8),
                          boxShadow: [
                            BoxShadow(
                              blurRadius: 16, //阴影范围
                              spreadRadius: 1, //阴影浓度
                              color: Color(0x16479DE4), //阴影颜色
                            )
                          ])),
                      onTap: () {
                        bool _isLogin = isEmpty(UserInfoUtils.getUserToken());
                        if (_isLogin) {
                          Navigator.pushNamed(context, "/LoginPageView");
                          return;
                        }
                        Navigator.pushNamed(context, "/FQPageView");
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5),
                      child: JText(
                        '发起',
                        color: Color(0xff3A4A61),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Column(
                  children: [
                    InkWell(
                      child: Container(child: Image.asset(
                        "img/home_cy.png",
                        width: Dimens.dimens50,
                        height: Dimens.dimens50,
                      ), decoration: BoxDecoration(
                          color: Color(0x00f6f7f8),
                          boxShadow: [
                            BoxShadow(
                              blurRadius: 16, //阴影范围
                              spreadRadius: 1, //阴影浓度
                              color: Color(0x16479DE4), //阴影颜色
                            )
                          ])),
                      onTap: () {
                        bool _isLogin = isEmpty(UserInfoUtils.getUserToken());
                        if (_isLogin) {
                          Navigator.pushNamed(context, "/LoginPageView");
                          return;
                        }
                        Navigator.pushNamed(context, "/CyPageView");
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5),
                      child: JText(
                        '参与',
                        color: Color(0xff3A4A61),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: Container(
            margin: EdgeInsets.only(top: 22),
            height: ScreenUtil.getScreenH(context),
            decoration: BoxDecoration(
              borderRadius: new BorderRadius.all(Radius.circular(16.0)),
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [SQColor.white, Color(0xffF4F5F7)]),
            ),
            child: Column(
              children: [_gztView(), _yhView()],
            ),
          ),
        ),
      ],
    );
  }

  _gztView() {
    return Container(
      margin: EdgeInsets.only(top: 22),
      child: GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4, childAspectRatio: 1.2),
          itemCount: _gztData.length,
          itemBuilder: (context, index) {
            return InkWell(
              onTap: () {
                _itemClick(_gztData[index]);
              },
              child: Column(
                children: [
                  Image.asset(
                    "img/home_${_gztData[index]}.png",
                    width: 40,
                    height: 40,
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 5),
                    child: JText(
                      _gztData[index],
                      color: Color(0xff3A4A61),
                      fontSize: 13,
                    ),
                  ),
                ],
              ),
            );
          }),
    );
  }

  _itemClick(String title) {
    bool _isLogin = isEmpty(UserInfoUtils.getUserToken());
    if (_isLogin) {
      Navigator.pushNamed(context, "/LoginPageView");
      return;
    }
    switch (title) {
      case '创建任务':
        Navigator.pushNamed(context, '/CreateRWView', arguments: {});
        break;
      case '隐患登记':
        Navigator.pushNamed(context, '/YhdjPageView', arguments: '');
        break;
      case '排查任务':
        Navigator.pushNamed(context, '/PcrwView');
        break;
      case '隐患治理':
        Navigator.pushNamed(context, '/YhzlView');
        break;
      default:
    }
  }

  _yhView() {
    return Column(
      children: [
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.only(left: 15, top: 25),
          child: Center(child: Row(
            children: [
              Container(
                width: 3,
                height: 15,
                decoration: BoxDecoration(
                    borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                    color: SQColor.theme_color),
              ),
              Container(
                margin: EdgeInsets.only(left: 5,bottom: 2),
                child: JText('隐患治理情况', color: SQColor.black_333333, fontSize: 14, fontWeight: FontWeight.w500,),
              ),
            ],
          ),),
        ),
        Container(
          padding: EdgeInsets.only(left: 6, right: 6),
          child: GridView.builder(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, childAspectRatio: 1.9),
              itemCount: 4,
              itemBuilder: (context, index) {
                return GestureDetector(
                    onTap: () {},
                    child: Container(
                        decoration: BoxDecoration(
                            boxShadow: [
                              BoxShadow(
                                blurRadius: 16, //阴影范围
                                spreadRadius: 1, //阴影浓度
                                color: Color(0x063A68AF), //阴影颜色
                              )
                            ]),
                      margin: EdgeInsets.only(left: 6, top: 15, right: 6),
                      child: Image.asset(
                        "img/yhzl_${index + 1}.png",
                        width: Dimens.dimens50,
                        height: Dimens.dimens50,fit: BoxFit.fill,
                      ),
                    ));
              }),
        )
      ],
    );
  }

  bool isDownloading = false;
  String apkPath = "";
  int count, total;
  // 提示框
  _askedToLead(BuildContext context, CheckVersion version) {
    StatefulBuilder sb = StatefulBuilder(
      builder: (context, mSetState) {
        return WillPopScope(
          child: new AlertDialog(
            title: new Text("版本更新"),
            content: _dialogBody(version.updateDescribe),
            actions: <Widget>[
              new FlatButton(
                  child: Text(isDownloading ? "取消" : "现在更新"),
                  onPressed: () {
                    mSetState(() {
                      if (!isDownloading) {
                        isDownloading = true;
                        if (version.downloadUrl == "") {
                          this.count = 0;
                          this.total = 0;
                          isDownloading = false;
                          ToastUtils.showToast("下载地址为空");
                        } else {
                          _download(
                              context, version.downloadUrl, mSetState);
                        }
                      } else {
                        this.count = 0;
                        this.total = 0;
                        isDownloading = false;
                        Navigator.of(context).pop();
                        if (version.forceUpdate == 1) {
                          // 强制更新退出登录
                          exit(0);
                        }
                      }
                    });
                  }),
              Offstage(
                offstage: isDownloading,
                child: new FlatButton(
                    child: new Text("稍后再说"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      if (version.forceUpdate == 1) {
                        // 强制更新退出登录
                        exit(0);
                      }
                    }),
              )
            ],
          ),
          onWillPop: () async {
            return Future.value(false);
          },
        );
      },
    );
    showDialog(
        context: context, barrierDismissible: false, builder: (context) => sb);
  }

  _dialogBody(String words) {
    if (isDownloading) {
      try {
        int progress = (count / total * 100).toInt();
        return Text("下载进度：$progress%");
      } catch (e) {
        return Text("下载进度：0%");
      }
    } else {
      List<String> list = List();
      list.addAll(words.split("<abc>"));

      return SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: _getItems(list),
        ),
      );
    }
  }


  List<Widget> _getItems(List<String> list) {
    // 不带分割线的item
    List<Widget> items = new List();
    for (int i = 0; i < list.length; i++) {
      items.add(Container(
        padding: EdgeInsets.only(top: Dimens.dimens4, bottom: Dimens.dimens4),
        child: Text(list[i]),
      ));
    }
    return items;
  }

  //开始下载附件
  void _download(
      BuildContext context, String downPath, StateSetter mSetState) async {
    String result =
    await PerUtils.checkPermission(context, [Permission.storage]);
    if (result == "1") {
      final dir = await getExternalStorageDirectory();
      apkPath = dir.path + '/ehs3.apk';
      print(apkPath);
      File file = new File(apkPath);
      if (await file.exists()) {
        await file.delete();
      }
      BaseOptions _options = new BaseOptions(
          connectTimeout: 50000,
          receiveTimeout: 100000,
          headers: {"cache-control": "no-chache"});

      Dio dio = new Dio(_options);
      Response response = await dio.download(downPath, apkPath,
          onReceiveProgress: (count, total) {
            mSetState(() {
              this.count = count;
              this.total = total;
              if (count == total) {
                // 下载完毕
                ApkUpdataUtils.install(apkPath);
                isDownloading = false;
                Navigator.of(context).pop();
              }
            });
          });
    } else {
      ToastUtils.showToast("请先开启权限再下载");
    }
  }

}
